<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Shipping extends AdminController
{
    public $_validation = null;

    function __construct()
    {
        parent::__construct();
        $this->load->model('MShop');
        $this->load->model('MAdmin');
        $allShops = $this->MShop->getAllShopsTrue();
        $this->load->model('MStorageShipping');
        $this->_validation = Array(
            array('field' => 'record_ids', 'label' => '包含物品', 'rules' => 'max_length[255]')
        , array('field' => 'operator_id', 'label' => '发货人', 'rules' => 'max_length[255]')
        , array('field' => 'shop_id', 'label' => '所属账户', 'rules' => 'required')
        , array('field' => 'shipping_number', 'label' => '物流单号', 'rules' => 'required')
        , array('field' => 'shipping_desc', 'label' => '发货方式', 'rules' => 'required')
        , array('field' => 'location', 'label' => '发货仓库', 'rules' => 'required')
        , array('field' => 'cost', 'label' => '成本', 'rules' => 'required')
        , array('field' => 'freight', 'label' => '运费', 'rules' => '')
        , array('field' => 'boxs', 'label' => '打包箱数', 'rules' => '')
        , array('field' => 'shipping_time', 'label' => '发货时间', 'rules' => '')
        , array('field' => 'status', 'label' => '状态', 'rules' => '')
        , array('field' => 'remark', 'label' => '备注', 'rules' => '')
        , array('field' => 'create_time', 'label' => '创建时间', 'rules' => '')
        , array('field' => 'update_time', 'label' => '更新时间', 'rules' => '')
        );
        $allPurchaser = $this->MAdmin->getAllPurchaser();
        $this->assign('allShops', $allShops);
        $this->assign('allPurchaser', $allPurchaser);
    }

    public function index()
    {
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $this->formfilter->addFilter('shop_id', 'where');
        $this->formfilter->addFilter('shipping_number', 'where');
        $this->formfilter->addFilter('location', 'where');
        $this->formfilter->addFilter('status', 'where');

        if ($begintime = filterValue('shipping_create_time_begin')) {
            $this->formfilter->addFilter('shipping_create_time_begin', 'where', array('create_time >= ', strtotime($begintime . ' 00:00:00')));
        }
        if ($endtime = filterValue('shipping_create_time_end')) {
            $this->formfilter->addFilter('shipping_create_time_end', 'where', array('create_time <= ', strtotime($endtime . ' 23:59:59')));
        }

        $number_perpage = filterValue('shipping_number_perpage');
        $order_type = filterValue('shipping_order_type');

        $total_number = $this->MStorageShipping->getCount();
        $limit = $this->pagination($total_number, '', $number_perpage);
        $list = $this->MStorageShipping->getList($limit, $order_type);

        $this->assign('list', $list);
        $this->layout();
    }

    public function add()
    {
        $data = $this->input->post();
        if (!isset($data['apply_ids'])) {
            errorAndRedirect('出库记录无效！');
        }
        $id_str = implode(',', $data['apply_ids']);

        $this->load->model('MStorageRecord');

        $list = $this->MStorageRecord->getByIds($id_str);
        $locationArr = array();
        foreach ($list as $v){
            $locationArr[] = $v->location;
        }
        if (count(array_unique($locationArr)) > 1){
            errorAndRedirect('所选出库记录不在同一仓库，不可进行打包发货！',site_url('storage/shipping/deliver'));
        }

        $amount = 0;
        foreach ($list as $l_v){
            $amount += $l_v->amount;
        }

        $this->assign('list', $list);
        $this->assign('ids', $id_str);
        $this->assign('amount', $amount);
        $this->layout();
    }

    public function add_post()
    {
        $obj = $this->MStorageShipping->createVo();
        $obj->create_time = time();
        $obj->update_time = time();
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);

        if ($this->form_validation->run() == TRUE) {
            $this->db->trans_start();//开启事务

            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            $newObj->shipping_time = strtotime($this->input->post('shipping_time'));
            if ($this->MStorageShipping->add($newObj)) {
                $this->load->model('MStorageRecord');
                $this->MStorageRecord->updateRecordDeliver($this->input->post('record_ids'),$newObj->shipping_number);
            } else {
                $this->db->_trans_status = FALSE;
            }

            $this->db->trans_complete();
            if ($this->db->trans_status() !== FALSE) {
                successAndRedirect('添加记录成功');
            } else {
                errorAndRedirect('添加失败');
            }
        } else {
            errorAndRedirect($this->form_validation->error_string(), site_url('storage/shipping/deliver'));
        }
    }

    function edit($id)
    {
        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $obj = $this->MStorageShipping->getOne(Array('id' => $id));
        if (!$obj) {
            errorAndRedirect('未找到定义！');
        }
        $this->editObj = $obj;
        $this->load->library('form_validation');
        $this->form_validation->set_rules($this->_validation);
        if ($this->form_validation->run() == TRUE) {
            $this->load->helper('populate');
            $newObj = populate((Object)((Array)$obj), $this->form_validation->post());
            $newObj->shipping_time = strtotime($newObj->shipping_time);
            if ($this->MStorageShipping->update($newObj)) {

                $content = '';
                foreach ($newObj as $key =>$value){

                    if ($key == 'cost' || $key== 'freight' || $key == 'shipping_time'){
                        $newObj->$key = (float)$newObj->$key;
                        $obj->$key = (float)$obj->$key;
                    }
                    if ($newObj->$key !== $obj->$key && $key !== 'update_time'){

                        //修改运单号之后，更新出库记录中运单号
                        if ($key == 'shipping_number'){
                            $this->load->model('MStorageRecord');
                            $list = $this->MStorageRecord->getAll(['shipping_no' => $obj->shipping_number]);
                            foreach ($list as $v){
                                $v->shipping_no = $newObj->shipping_number;
                                $this->MStorageRecord->update($v);
                            }
                        }

                        if ($key == 'shipping_time'){
                            $obj->shipping_time = date('Y-m-d',$obj->shipping_time);
                            $newObj->shipping_time = date('Y-m-d',$newObj->shipping_time);
                        }

                        //给数字赋值
                        if ($key == 'shop_id'){
                            $allShops = $this->MShop->getAllShopsTrue();
                            $obj->shop_id = $allShops[$obj->shop_id];
                            $newObj->shop_id = $allShops[$newObj->shop_id];
                        }
                        if ($key == 'location'){
                            $obj->location == 1? $obj->location ='合肥':$obj->location='深圳' ;
                            $newObj->location == 1? $newObj->location ='合肥':$newObj->location='深圳' ;
                        }

                        $content .= ' '.IOSS_StaticConfig::translateLogField($key).' 由 '.$obj->$key.' 改为 '.$newObj->$key.';';
                    }
                }
                if ($content){
                    $this->editLog($this->_user->id,$id,$this->_thisModule.$this->_thisController.'/'.$this->_thisMethod,$content);
                }

                successAndRedirect(l('edit_success'));
            } else {
                errorAndRedirect(l('data_fail'));
            }
        }else{
            errorAndRedirect($this->form_validation->error_string());
        }
    }

    function view($id)
    {
        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $this->load->model('MStorageShipping');
        $obj = $this->MStorageShipping->getOne(Array('id' => $id));

        if (!$obj) {
            errorAndRedirect('未找到定义！');
        }
        //该任务的所有操作记录
        $this->load->model('MStorageRecord');
        $allRecords = $this->MStorageRecord->getAllRecord($obj->record_ids);

        $this->assign('obj', $obj);
        $this->assign('allRecords', $allRecords);
        $this->layout('view.tpl');
    }

    function delete($id, $update_time)
    {
        if (!is_numeric($id) || !is_numeric($update_time)) {
            show_error(l('id_not_null'));
        }
        if (!$this->MTask->delete($id, $update_time)) {
            errorAndRedirect(l('data_fail'));
        }
        successAndRedirect(l('delete_success'));
    }

    function deliver()
    {
        $this->load->library('FormFilter');
        $this->load->helper('formfilter');
        $this->formfilter->addFilter('r.order_no', 'where');
        $this->formfilter->addFilter('r.order_no', 'where');
        $this->formfilter->addFilter('p.product_name', 'like');
        $this->formfilter->addFilter('r.shop_id', 'where');
        $this->formfilter->addFilter('r.product_id', 'where');
        $this->formfilter->addFilter('r.type_mark', 'where');
        $this->formfilter->addFilter('w.location', 'where');

        if ($begintime = filterValue('record_create_time_begin')) {
            $this->formfilter->addFilter('record_create_time_begin', 'where', array('r.create_time >= ', strtotime($begintime . ' 00:00:00')));
        }
        if ($endtime = filterValue('record_create_time_end')) {
            $this->formfilter->addFilter('record_create_time_end', 'where', array('r.create_time <= ', strtotime($endtime . ' 23:59:59')));
        }

        $number_perpage = filterValue('record_number_perpage');
        $order_type = filterValue('record_order_type');

        $this->load->model('MAdmin');
        $this->load->model('MStorageRecord');
        $total_number = $this->MStorageRecord->getDeliverCount();
        $limit = $this->pagination($total_number, '', $number_perpage);
        $list = $this->MStorageRecord->getDeliverList($limit, $order_type);
        $allPurchaser = $this->MAdmin->getAllPurchaser();

        $this->load->model('MStorageProduct');
        $allProducts = $this->MStorageProduct->getAllProducts();
        $this->assign('list', $list);
        $this->assign('allPurchaser', $allPurchaser);
        $this->assign('allProducts', $allProducts);
        $this->layout();
    }

    public function shipping_fail($id)
    {
        if (!is_numeric($id)) {
            show_error(l('id_not_null'));
        }
        $this->db->trans_start();
        $shipping = $this->MStorageShipping->getOne(['id' => $id]);
        $shipping->status = 0;
        if ($this->MStorageShipping->update($shipping)) {
            $this->load->model('MStorageRecord');
            $outRecords = $this->MStorageRecord->getAllRecord($shipping->record_ids);
            if (!$outRecords) {
                $this->db->_trans_status = FALSE;
                errorAndRedirect('无该物流出库记录！');
            } else {
                $this->MStorageRecord->updateRecordUnDeliver($shipping->record_ids);
            }
        } else {
            $this->db->_trans_status = FALSE;
        }
        $this->db->trans_complete();
        if ($this->db->_trans_status !== FALSE) {
            successAndRedirect('操作成功，已经该物流内出库记录变更为待发货！');
        } else {
            errorAndRedirect('操作失败！');
        }
    }

    public function ajaxDetail(){
        $detail = $this->MStorageShipping->getById($this->input->post('id'));
        $detail->shipping_time = date('Y-m-d',$detail->shipping_time);
        exit(json_encode($detail));
    }

}
